/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */
// #ifdef MP-WEIXIN
const FormData = require('@/common/wx-formdata-master/formData.js')
// #endif
let HTTP_URL = ''
export default {
    config: {
        baseUrl: '',
        header: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        data: {},
        method: "GET",
        dataType: "json", /* 如设为json，会对返回的数据做一次 JSON.parse   text*/
        responseType: "text",
        success() {},
        fail() {},
        complete() {},
    },
    interceptor: {
        request: null,
        response: null
    },
    request(options,toast) {
		//动态判断环境
		if(process.env.NODE_ENV === 'development'){
			// console.log('===开发环境');
			HTTP_URL = 'https://ythsxxkj.com/api/'
		}else{
		}
        if(!toast || toast == 'loading'){
        	uni.showLoading({
        	    title: '请稍候...'
        	})
        }
        if (!options) {
            options = {}
        }
        options.baseUrl = HTTP_URL
        options.dataType = options.dataType || this.config.dataType
        options.url = options.baseUrl + options.url
		
        options.data = options.data || {}
        options.method = options.method || this.config.method
        options.header = options.header || this.config.header
		
		const token = uni.getStorageSync('token') || ''
		if(token){
			options.header = Object.assign({}, options.header, {
				'token': token
			})
		}

        if (options.method === 'POSTBODY') {
            options.method = 'POST';
            options.header = Object.assign({}, options.header, {
                'Content-Type': 'application/json;charset=UTF-8'
            })
            let params = options.data
            const formData = new FormData();
            Object.keys(params).forEach((key) => {
                formData.append(key, params[key]);
            });
            options.body = formData;
        }
        return new Promise((resolve, reject) => {
            let _config = null

            options.complete = (response) => {
				if(!toast || toast == 'loading'){
					uni.hideLoading();
				}
                let statusCode = response.statusCode
                response.config = _config
                if (this.interceptor.response) {
                    let newResponse = this.interceptor.response(response)
                    if (newResponse) {
                        response = newResponse
                    }
                }
                // 统一的响应日志记录
                _reslog(response)
                //成功
                if (statusCode === 200) {
					if (response.data.code === 401) {
						uni.navigateTo({
							url: '/pages/login/login'
						})
                    } 
					else if (response.data.code === 200) {
                        //正常
                        resolve(response.data);
                    }else{
					  //处理自己的异常
					  uni.showToast({
						  title: response.data.message,
						  icon: 'none',
						  duration: 4000
					  })  
                    }
                } else {
                    //接口报错
                    console.log("报错接口=>" + options.url);
					uni.showToast({
						title: '[FAIL]' + response.data.message,
						icon: 'none',
						duration: 2000
					})
					reject(response.data)
                }
            }

            _config = Object.assign({}, this.config, options)
            _config.requestId = new Date().getTime()

            if (this.interceptor.request) {
                this.interceptor.request(_config)
            }

            // 统一的请求日志记录
            _reqlog(_config)
            uni.request(_config);
        });
    },
    get(url, data, toast, options) {
        if (!options) {
            options = {}
        }
        options.url = url
        options.data = data
        options.method = 'GET'
        return this.request(options, toast)
    },
    post(url, data, toast, options) {
        if (!options) {
            options = {}
        }
        options.url = url
        options.data = data
        options.method = 'POST'
        return this.request(options, toast)
    },
    postBody(url, data, toast, options) {
        if (!options) {
            options = {}
        }
        options.url = url
        options.data = data
        options.method = 'POSTBODY'
        return this.request(options, toast)
    },
    put(url, data, options) {
        if (!options) {
            options = {}
        }
        options.url = url
        options.data = data
        options.method = 'PUT'
        return this.request(options)
    },
    delete(url, data, options) {
        if (!options) {
            options = {}
        }
        options.url = url
        options.data = data
        options.method = 'DELETE'
        return this.request(options)
    },
    uploadImgFile(url, id, data, resolve) {
        let token = uni.getStorageSync('token');
        uni.showLoading({
            title: '请稍候...'
        })
        let header = {
            'Content-Type': 'application/json;charset=UTF-8',
        };
        console.log("=============>" + HTTP_URL + url)
        return uni.uploadFile({
            url: HTTP_URL + url, // 需要上传的地址
			// #ifdef APP-PLUS
            header: header,
			// #endif
            formData: {
				'activity_id': id,
                'token': token.api_token
            },
            filePath: data, // filePath  需要上传的文件
            name: 'file',
            success(res1) {
                uni.hideLoading();
                resolve(res1.data);
            },
            fail(res) {
                console.log(res)
            }
        });
    },
    uploadImgFileForHttp(url, data, token, resolve) {
        uni.showLoading({
            title: '请稍候...'
        })
        let header = {
            'Content-Type': 'application/x-www-form-urlencoded',
        };
        console.log("=============>" + HTTP_URL + url)
        return uni.uploadFile({
            url: url, // 需要上传的地址
            header: header,
            formData: {
                'token': token
            },
            filePath: data, // filePath  需要上传的文件
            name: 'file',
            success(res1) {
                uni.hideLoading();
                resolve(res1.data);
            }
        });
    }
}


/**
 * 请求接口日志记录
 */
function _reqlog(req) {
    // if (process.env.NODE_ENV === 'development') {
    // 	console.log("【" + req.requestId + "】 地址：" + req.url)
    // 	if (req.data) {
    // 		console.log("【" + req.requestId + "】 请求参数：" + JSON.stringify(req.data))
    // 	}
    // }
    //TODO 调接口异步写入日志数据库
}

/**
 * 响应接口日志记录
 */
function _reslog(res) {
    let _statusCode = res.statusCode;
    if (process.env.NODE_ENV === 'development' && false) {
        console.log("【" + formatDate(res.config.requestId) + "】 地址：" + res.config.url)
        if (res.config.data) {
            console.log("【" + formatDate(res.config.requestId) + "】 请求参数：" + JSON.stringify(res.config.data))
        }
        //console.log("【" + formatDate(res.config.requestId) + "】 响应结果：" + JSON.stringify(res))
    }
    //TODO 除了接口服务错误外，其他日志调接口异步写入日志数据库
    switch (_statusCode) {
        case 200:
            break;
        case 401:
            break;
        case 404:
            break;
        default:
            break;
    }
}